<template>
  <div class="divBox">
    <el-card class="box-card">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
          <el-form v-loading="saveLoading" ref="form" :model="form" :rules="rules" label-width="120px" @submit.native.prevent>
            <el-form-item label="头像：" prop="faceUrl">
              <el-upload
                  class="avatar-uploader"
                  action
                  :disabled="isDisabled"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :http-request="handleUploadForm"
                  :headers="myHeaders"
                  :before-upload="beforeAvatarUpload">
                <img v-if="form.faceUrl" :src="imageUrl + form.faceUrl" class="avatar" alt="">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="姓名：" prop="tenantName">
              <el-input v-model="form.tenantName" placeholder="姓名" style="width: 50%" :disabled="isDisabled"
              ></el-input>
            </el-form-item>
            <el-form-item label="身份证号" prop="tenantIdCard">
              <el-input v-model="form.tenantIdCard" placeholder="身份证号"  style="width: 50%" :disabled="isDisabled"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="tenantPhone">
              <el-input v-model="form.tenantPhone" placeholder="联系方式" style="width: 50%" :disabled="isDisabled"
              ></el-input>
            </el-form-item>
            <el-form-item label="实名状态" prop="faceAuthenticationTime">
              <el-select
                  v-model="currentFaceStatus"
                  placeholder="实名状态"
                  style="width: 50%"
                  :disabled="isDisabled"
                  @change="handleFaceStatusChange"
              >
                <el-option
                    v-for="item in faceOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
<!--            <el-form-item label="说明：" prop="buildingNumber">-->
<!--              <el-input-->
<!--                  type="textarea"-->
<!--                  v-model="form.buildingNumber"-->
<!--                  style="width: 50%"-->
<!--                  :disabled="isDisabled"-->
<!--                  maxlength="300"-->
<!--                  show-word-limit-->
<!--                  class="custom-textarea"-->
<!--              ></el-input>-->
<!--            </el-form-item>-->

            <el-form-item>
              <el-button v-loading="saveLoading" element-loading-background="rgba(0, 0, 0, 0.3)" type="primary"
                         @click="handlerSubmit" v-has-permi="['admin:lessee:save']">保存
              </el-button>
              <el-button @click="close">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="房屋信息" name="second">
          <House :id="form.id" :uniqueId="form.uniqueId" :isDisabled="isDisabled" ></House>
        </el-tab-pane>
        <el-tab-pane label="租赁情况" name="third">
          <LeaseSituation :id="form.id"  :isDisabled="isDisabled"></LeaseSituation>
        </el-tab-pane>
      </el-tabs>

    </el-card>

  </div>
</template>
<script>

import {upload} from "@/api/upload";
import {getToken} from "@/utils/auth";
import LeaseSituation from "@/views/lessee/components/houseSituation.vue";
import House from "@/views/lessee/components/house.vue";
import {save, detail} from "@/api/lessee";

export default {
  components: {House, LeaseSituation},

  data() {
    return {
      isDisabled: this.$route.params.isDisabled==='1'?true:false,
      activeName: 'first',
      form: {
        id: null,
        faceUrl:'',
        tenantIdCard:'',
        tenantName:'',
        tenantPhone:'',
        faceAuthenticationTime:'',
      },
      rules: {
        faceUrl: [{required: true, message: '请上传头像', trigger: ['blur']}],
        tenantIdCard: [{required: true, message: '请填写身份证号', trigger: ['blur']}],
        tenantName: [{required: true, message: '请填写姓名', trigger: ['blur']}],
        tenantPhone: [{required: true, message: '请填写联系电话', trigger: ['blur']}],
      },
      saveLoading: false,
      formLoading: false,
      faceOptions: [
        { value: '已实名', label: '已实名' },
        { value: '未实名', label: '未实名' }
      ],
      myHeaders: {"token": getToken()},
      imageUrl: '',
    }
  },
  computed: {
    // 根据faceAuthenticationTime的值计算当前显示状态
    currentFaceStatus: {
      get() {
        return this.form.faceAuthenticationTime ? '已实名' : '未实名'
      }
    }
  },
  mounted() {
    this.imageUrl = process.env.VUE_APP_IMAGE_URL
    if (this.$route.params.id) {
      this.getDetail();
    }
  },
  methods: {
    getDetail() {
      // 这里可以添加获取房屋详情的逻辑，发送API请求获取数据
      this.saveLoading = true;
      detail(this.$route.params.id).then((res) => {
        this.form = res
        this.close();
      }).finally(() => {
        this.saveLoading = false
      })
    },
    handlerSubmit() {
      if (this.saveLoading) {
        return
      }
      this.$refs.form.validate(valid => {
        if (!valid) return;
        this.saveLoading = true;
        save(this.form).then(() => {
          this.$message.success('保存成功');
          this.close();
        }).finally(() => {
          this.saveLoading = false
        })
      })
    },
    handleAvatarSuccess(res, file) {
      this.form.faceUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG、PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleUploadForm(param) {
      const formData = new FormData();
      //0=>maintain 全部
      formData.append("file", param.file);
      let loading = this.$loading({
        lock: true,
        text: "上传中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      upload(formData)
          .then((res) => {
            this.form.faceUrl = res
            //图片上传接口 后期调用
            loading.close();
            this.$message.success("上传成功");
          }).catch((res) => {
        loading.close();
      });
    },
    handleFaceStatusChange(val) {
      if (val === '已实名') {
        this.form.faceAuthenticationTime = new Date().toISOString() // 设置为当前ISO时间
      } else {
        this.form.faceAuthenticationTime = null // 设置为null
      }
    },
    close() {
      this.$emit('hideEditDialog');
    },
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}



::v-deep .el-textarea .el-input__count {
  position: absolute;
  right: -50px;
  bottom: 0;
  background: transparent;
}
</style>
